﻿using System;
using ITViet.Domains;
using ITViet.Services;
using ITViet.Web.App_Code;
using Library.Logging;
using System.Web;
using System.IO;

namespace ITViet.Web
{
  public class Global : HttpApplication
  {
    protected void Application_Start(object sender, EventArgs e)
    {

    }

    protected void Session_Start(object sender, EventArgs e)
    {
      try
      {
        Setting setting = GlobalCache.Instance.GetSettingById((int)SettingList.PAGE_VIEW) ?? new Setting();
        setting.Value = (int.Parse(setting.Value) + 1).ToString();
        new SettingService().Save(setting);
        GlobalCache.Instance.LoadDBSetting();

        #region Delete Temp
        string tempFolder = App_Code.FolderDirector.TempFolder;
        tempFolder = Request.MapPath(tempFolder);
        string[] filePaths = Directory.GetFiles(tempFolder);
        if (filePaths == null || filePaths.Length == 0)
          return;
        foreach (string file in filePaths)
        {
          File.Delete(file);
        }
        #endregion
      }
      catch (Exception ex)
      {
        Logger.LogError("Global.asax::Increase counter", ex, "General", null);
      }
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
      try
      {
        string session_param_name = "ASPSESSID";
        string session_cookie_name = "ASP.NET_SESSIONID";

        if (HttpContext.Current.Request.Form[session_param_name] != null)
        {
          UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
        }
        else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
        {
          UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
        }
      }
      catch (Exception)
      {
        Response.StatusCode = 500;
        Response.Write("Error Initializing Session");
      }
    }

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {

    }

    protected void Application_Error(object sender, EventArgs e)
    {

    }

    protected void Session_End(object sender, EventArgs e)
    {

    }

    protected void Application_End(object sender, EventArgs e)
    {

    }

    private void UpdateCookie(string cookieName, string cookieValue)
    {
      HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName);
      if (cookie == null)
      {
        cookie = new HttpCookie(cookieName);
        HttpContext.Current.Request.Cookies.Add(cookie);
      }
      cookie.Value = cookieValue;
      HttpContext.Current.Request.Cookies.Set(cookie);
    }
  }
}